<template>
  <a-modal v-model:visible="visible" :title="title" :maskClosable="false" :footer="null">
    <a-form :label-col="labelCol">
      <a-form-item label="角色名称" v-bind="validateInfos.name">
        <a-input v-model:value="formState.name" placeholder="请输入角色名称" />
      </a-form-item>
      <a-row>
        <a-col :md="10" :xs="24">
          <a-form-item label="角色级别">
            <a-input-number v-model:value="formState.level" :min="1" />
          </a-form-item>
        </a-col>
        <a-col :md="14" :xs="24">
          <a-form-item label="数据范围">
            <a-select
              v-model:value="formState.dataScope"
              placeholder="请选择数据范围"
              @change="changeScope"
            >
              <a-select-option v-for="item in dateScopes" :key="item" :value="item">{{
                item
              }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item label="数据权限" v-if="formState.dataScope === '自定义'">
        <a-tree-select
          v-model:value="formState.depts"
          style="width: 100%"
          :tree-data="deptOptions"
          :load-data="onLoadData"
          tree-checkable
          allow-clear
          :show-checked-strategy="SHOW_PARENT"
          placeholder="请选择"
          :field-names="replaceFields"
        />
      </a-form-item>
      <a-form-item label="描述信息">
        <a-textarea v-model:value="formState.description" placeholder="请输入描述信息" />
      </a-form-item>
      <a-form-item style="margin-bottom: 0px; margin-top: 40px; text-align: right">
        <a-button type="primary" @click.prevent="onSubmit">确认</a-button>
        <a-button style="margin-left: 10px" @click="resetFields">重置</a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, watch, toRaw } from 'vue';
  import { TreeSelect, Form, message, notification } from 'ant-design-vue';
  import { getDeptsApi, getDeptSuperiorApi } from '/@/api/dept';
  import { editRoleApi, addRoleApi } from '/@/api/role';
  import { reload, buildDepts } from './index';

  const SHOW_PARENT = TreeSelect.SHOW_PARENT;
  const replaceFields = {
    children: 'children',
    title: 'name',
    value: 'id',
    isLeaf: 'leaf',
  };

  const dateScopes = ['全部', '本级', '自定义'];

  const formState = reactive({
    id: null,
    name: null,
    depts: [] as any,
    description: null,
    dataScope: '全部',
    level: 3,
  });
  const rulesRef = reactive({
    name: [
      {
        required: true,
        message: '角色名称不能为空',
      },
    ],
  });
  const useForm = Form.useForm;
  const { resetFields, validate, validateInfos } = useForm(formState, rulesRef);

  export default defineComponent({
    setup() {
      const visible = ref<boolean>(false);
      const title = ref<string>('');
      watch(visible, (newVal, _oldVal) => {
        if (!newVal) {
          resetFields();
        }
      });

      const deptOptions = ref<any>([]);
      const getDepts = async (params) => {
        const res = await getDeptsApi({ ...params, enabled: true });
        const data = res.content.map(function (obj) {
          if (obj.leaf) {
            obj.isLeaf = obj.leaf;
          }
          if (obj.hasChildren) {
            obj.children = [];
          }
          return obj;
        });
        return data;
      };

      const open = async (isAdd: boolean, record) => {
        if (isAdd) {
          title.value = '新增角色';
        } else {
          title.value = '编辑角色';
          formState.id = record.id;
          formState.level = record.level;
          formState.name = record.name;
          formState.dataScope = record.dataScope;
          record.depts.forEach(function (item) {
            formState.depts.push(item.id);
          });
          formState.description = record.description;
          if (formState.dataScope === '自定义') {
            const res = await getDeptSuperiorApi(formState.depts);
            const data = res?.content || [];
            buildDepts(data);
            deptOptions.value = data;
          }
        }
        visible.value = true;
      };

      const onLoadData = (treeNode: any) => {
        return new Promise((resolve: (value?: unknown) => void) => {
          if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
            resolve();
            return;
          }
          setTimeout(async () => {
            const id = treeNode.dataRef.id;
            const data = deptOptions.value;
            let response = await getDepts({
              pid: id,
            });
            //获取到的子节点
            const children = response ?? [];
            const dataMap = (items: Array<any>) => {
              items.find((item) => {
                if (item.id === id) {
                  //找到当前要展开的节点
                  item.children = children;
                  return items;
                }
                if (item.children && item.children.length > 0) {
                  dataMap(item.children);
                }
              });
            };
            dataMap(data || []);
            deptOptions.value = data;
            resolve(true);
          }, 200);
        });
      };

      const onSubmit = (_e: MouseEvent) => {
        validate()
          .then(async () => {
            if (formState.dataScope === '自定义' && formState.depts.length === 0) {
              message.warning('自定义数据权限不能为空');
              return;
            } else if (formState.dataScope != '自定义') {
              formState.depts = [];
            }
            const obj = toRaw(formState);
            const depts: Array<{ id: number }> = [];
            obj.depts.forEach(function (data) {
              const item = { id: data };
              depts.push(item);
            });
            if (!!formState.id) {
              await editRoleApi({ ...obj, depts });
            } else {
              await addRoleApi({ ...obj, depts });
            }

            visible.value = false;
            reload.value = !reload.value;

            notification['success']({
              message: title.value + '成功!',
              duration: 3,
            });
          })
          .catch((err) => {
            console.log('error', err);
          });
      };

      // 如果数据权限为自定义则获取部门数据
      const changeScope = async () => {
        if (formState.dataScope === '自定义') {
          deptOptions.value = await getDepts({});
        }
      };

      return {
        replaceFields,
        onLoadData,
        SHOW_PARENT,
        labelCol: { style: { width: '80px' } },
        wrapperCol: { span: 14 },
        onSubmit,
        visible: visible,
        changeScope,
        dateScopes,
        formState,
        resetFields,
        validateInfos,
        deptOptions,
        title,
        open,
      };
    },
  });
</script>
